<template>
  <div class="user-info-edit-container">
    <el-card>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        @submit.prevent="handleSubmit"
      >
        <!-- 用户ID（隐藏或展示根据需求，通常从登录态获取） -->
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>

        <el-form-item label="联系地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入联系地址" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            :loading="isLoading" 
            :disabled="isLoading"
            native-type="submit"
          >
            {{ isLoading ? '保存中...' : '保存修改' }}
          </el-button>
        </el-form-item>

        <div v-if="errorMessage" class="error-message">
          <el-alert type="error" :title="errorMessage" show-icon />
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { updateUserInfo } from '@/api/user';
import { ElMessage } from 'element-plus';

// 表单数据（初始化从登录态获取）
const form = ref({
  userId: '', // 从localStorage或store获取当前用户ID
  name: '',
  address: '',
  phone: ''
});

// 加载状态和错误信息
const isLoading = ref(false);
const errorMessage = ref('');

// 表单校验规则
const rules = ref({
  userId: [
    { required: true, message: '用户ID不能为空', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在2-50字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }
  ]
});

// 表单引用
const formRef = ref(null);

// 初始化：从登录态获取用户信息
const initUserInfo = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo')); // 假设用户信息存在localStorage
  if (userInfo) {
    form.value = {
      userId: userInfo._id, // 假设用户ID字段为_id
      name: userInfo.name || '',
      address: userInfo.address || '',
      phone: userInfo.phone || ''
    };
  }
};

// 提交表单
const handleSubmit = async () => {
  isLoading.value = true;
  errorMessage.value = '';

  // 表单校验
  const valid = await new Promise(resolve => {
    formRef.value.validate(valid => resolve(valid));
  });

  if (!valid) {
    isLoading.value = false;
    return;
  }

  // 调用接口更新信息
  try {
    const res = await updateUserInfo(form.value);
    if (res.code === 200) {
      ElMessage.success('信息更新成功');
      // 更新localStorage中的用户信息（可选）
      const userInfo = JSON.parse(localStorage.getItem('userInfo'));
      localStorage.setItem('userInfo', JSON.stringify({ ...userInfo, ...form.value }));
    }
  } catch (err) {
    errorMessage.value = err.message || '信息更新失败';
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时初始化数据
initUserInfo();
</script>

<style scoped>
.user-info-edit-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.error-message {
  margin-top: 15px;
}
</style>
